package com.mvc.utils;

import com.mvc.dao.RoleDAO;
import com.mvc.entity.Role;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    public static SqlSessionFactory getSqlSessionFactory() {
        InputStream inputStream = null;
        if (sqlSessionFactory == null) {
            try {
                String resource = "mybatis-config.xml";
                sqlSessionFactory = new SqlSessionFactoryBuilder().build (Resources.getResourceAsStream(resource));
                return sqlSessionFactory;
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }

    public static SqlSessionFactory getSqlSessionFactoryHardCode() {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis");
        dataSource.setUsername("root");
        dataSource.setPassword("learn");
//构建数据库事务方式
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
//创建了数据库运行环境
        Environment environment = new Environment("development", transactionFactory, dataSource);
//构建Configuration对象
        Configuration configuration = new Configuration(environment);
//注册一个MyBatis上下文别名
        configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
//加入一个映射器
        configuration.addMapper(RoleDAO.class);
//使用SqlSessionFactoryBuilder构建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build (configuration);

        return sqlSessionFactory;
    }
}